//
//  ServiceManage.m
//  51-Tour
//
//  Created by xiang ying on 14-3-28.
//  Copyright (c) 2014年 xiang ying. All rights reserved.
//

#import "ServiceManage.h"
#import "tour_lib.h"
#import "NSString+TPCategory.h"
#import "amrFileCodec.h"
#import "NSDate+TPCategory.h"
#import "db_Downloading.h"
#import "SVProgressHUD.h"

@implementation ServiceManage

//提供zip解压方法
+(BOOL) UnzipOpenFile:(NSString*) zipFile{
    return [tour_lib UnzipOpenFile:zipFile];
}

//解析properties文件
//errorcode 0成功 -1文件不存在 2不是标准的properties文件
+ (void)parseProperties:(NSString*)filePath completion:(void(^)(NSInteger errCode,NSString *errorMsg,ScenicDTO *result))completion{
    [tour_lib parseProperties:filePath completion:^(NSInteger errCode, NSString *errorMsg, NSDictionary *result) {
        ScenicDTO *dto = nil;
        if (errCode == 0) {
            dto = [[ScenicDTO alloc] init];
            dto.vtg_language_id = result[@"languageId"];
            dto.vtg_language_key = result[@"languageKey"];
            dto.vtg_scenic_id = result[@"scenicId"];
            dto.GPS = CGPointMake([result[@"lng"] doubleValue], [result[@"lat"] doubleValue]);
            NSArray *array1 = [result[@"topLeft"] componentsSeparatedByString:@","];
            if (array1.count>1) {
                dto.top_left = CGPointMake([array1[0] doubleValue], [array1[1] doubleValue]);
            }
            NSArray *array2 = [result[@"bottomRight"] componentsSeparatedByString:@","];
            if (array2.count>1) {
                dto.bottom_right = CGPointMake([array2[0] doubleValue], [array2[1] doubleValue]);
            }
            dto.vtg_scenic_name = result[@"scenicName"];
            if (result[@"typeId"]) {
                dto.type = [result[@"typeId"] integerValue];
            }
            if (result[@"zoom"]) {
                dto.zoomScale = [result[@"zoom"] floatValue];
            }
        }
        completion(errCode,errorMsg,dto);
    }];
}

+(BOOL)checkNet{
    return [tour_lib checkNet];
}

//获取验证码
+(void)getRegisterCodeRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib getRegisterCodeRequestInfo:info completion:^(RespondDTO *respond) {
        completion(respond);
    }];
}

//注册或登录
+(void)setRegisterRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib setRegisterRequestInfo:info completion:^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            NSDictionary *dic = respond.data;
            UserDTO *user = [[UserDTO alloc] init];
            user.userPhone = info[@"Mobile"];
            user.code = info[@"ValidateCode"];
            user.sex = [dic[@"sex"] isKindOfClass:[NSString class]]?[dic[@"sex"] intValue]:0;
            user.userName = [dic[@"userName"] isKindOfClass:[NSString class]]?dic[@"userName"]:@"";
            if ([dic[@"icon"] isKindOfClass:[NSString class]]) {
                user.userIconPath = dic[@"icon"];
                if ([user.userIconPath isURLString]) {
                    dispatch_queue_t newThread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    dispatch_async(newThread, ^{
                        NSData *imagedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:user.userIconPath]];
                        [DataCenter instance].user.userIcon = [UIImage imageWithData:imagedata];
                        [imagedata writeToFile:ICONPATH atomically:YES];
                    });
                }
            }
            user.recommendNum = @"0";
            if (![dic[@"recommendNum"] isKindOfClass:[NSNull class]]) {
                user.recommendNum = dic[@"recommendNum"];
            }

            [[DataCenter instance] setUserInfo:user];
        }else{
            [[DataCenter instance] setUserInfo:nil];
        }
        completion(respond);
    }];
}

//用户信息
+(void)getRequestUserInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib getRequestUserInfo:info completion:^(RespondDTO *respond) {
        //NSLog(@"%@",respond.data);
        if (respond.flag == respond_success) {
            UserDTO *user = [[UserDTO alloc] init];
            [user copyfrom:[DataCenter instance].user];
            if (respond.data[@"guide"][@"guideLanguage"]) {
                user.GuideLan = ![respond.data[@"guide"][@"guideLanguage"] isKindOfClass:[NSNull class]]?respond.data[@"guide"][@"guideLanguage"]:@"";
            }else{
                user.GuideLan = @"";
            }
            user.tourNum = ![respond.data[@"guide"][@"guideNum"] isKindOfClass:[NSNull class]]?respond.data[@"guide"][@"guideNum"]:@"";
            user.tourExp = ![respond.data[@"guide"][@"guideWorkYear"] isKindOfClass:[NSNull class]]?respond.data[@"guide"][@"guideWorkYear"]:@"";
            
            user.card.cardNum = respond.data[@"bankcard"][@"account"];
            user.card.cardPerson = ![respond.data[@"bankcard"][@"owner"] isKindOfClass:[NSNull class]]?respond.data[@"bankcard"][@"owner"]:@"";
            user.card.cardPlace = ![respond.data[@"bankcard"][@"accountBank"] isKindOfClass:[NSNull class]]?respond.data[@"bankcard"][@"accountBank"]:@"";
            
           user.GuideCity = ![respond.data[@"guide"][@"guideCity"] isKindOfClass:[NSNull class]]?respond.data[@"guide"][@"guideCity"]:@"";
            
            user.sex = [respond.data[@"user"][@"sex"] integerValue];
            if ([respond.data[@"user"][@"icon"] isKindOfClass:[NSString class]]) {
                if (![user.userIconPath isEqualToString:respond.data[@"user"][@"icon"]]) {
                    user.userIconPath = respond.data[@"user"][@"icon"];
                    dispatch_queue_t newThread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    dispatch_async(newThread, ^{
                        NSData *imagedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:user.userIconPath]];
                        user.userIcon = [UIImage imageWithData:imagedata];
                        [imagedata writeToFile:ICONPATH atomically:YES];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"ICONCHANGE" object:@"ICONCHANGE"];
                    });
                }
            }else{
                user.userIcon = nil;
                user.userIconPath = @"";
            }
            
            if ([respond.data[@"guide"][@"guideIcon"] isKindOfClass:[NSString class]]) {
                if (![user.GuideIconPath isEqualToString:respond.data[@"guide"][@"guideIcon"]]) {
                    user.GuideIconPath = respond.data[@"guide"][@"guideIcon"];
                    dispatch_queue_t newThread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    dispatch_async(newThread, ^{
                        NSData *imagedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:user.GuideIconPath]];
                        user.GuideIcon = [UIImage imageWithData:imagedata];
                        [imagedata writeToFile:WORKICONPATH atomically:YES];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"WORKICONCHANGE" object:@"WORKICONCHANGE"];
                    });
                }
            }else{
                user.GuideIcon = nil;
                user.GuideIconPath = @"";
            }
            user.recommendNum = respond.data[@"user"][@"recommendNum"];
            user.userName = [respond.data[@"user"][@"userName"] isKindOfClass:[NSString class]]?respond.data[@"user"][@"userName"]:@"";
            [DataCenter instance].user = user;
        }
        completion(respond);
    }];
}

//修改信息
+(void)modifyRequestUserInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    //编码转换
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:info];
    
    [dic setObject:[info[@"UserName"] utf8Encodeing] forKey:@"UserName"];
    [dic setObject:[info[@"CardPerson"] utf8Encodeing] forKey:@"CardPerson"];
    [dic setObject:[info[@"GuideLan"] utf8Encodeing] forKey:@"GuideLan"];
    [dic setObject:[info[@"CardBank"] utf8Encodeing] forKey:@"CardBank"];
    [dic setObject:[info[@"GuideNum"] utf8Encodeing] forKey:@"GuideNum"];
    [dic setObject:[info[@"GuideCity"] utf8Encodeing] forKey:@"GuideCity"];

    [tour_lib modifyRequestUserInfo:dic completion:^(RespondDTO *respond) {
        completion(respond);
    }];
}

//添加银行卡
+(void)addCardRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib addCardRequestInfo:info completion:^(RespondDTO *respond) {
        completion(respond);
    }];
}

//用户银行卡列表
+(void)getCardsRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib getCardsRequestInfo:info completion:^(RespondDTO *respond) {
        completion(respond);
    }];
}

//用户反馈
+(void)feedBackRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:info];
    [dic setObject:[info[@"Content"] utf8Encodeing] forKey:@"Content"];
    [tour_lib feedBackRequestInfo:dic completion:^(RespondDTO *respond) {
        completion(respond);
    }];
}

//添加用户使用记录
+(void)addUserlogRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib addUserlogRequestInfo:info completion:^(RespondDTO *respond) {
        completion(respond);
    }];
}

//获取用户使用记录
+(void)getUserlogRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib getUserlogRequestInfo:info completion:^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            NSArray *array = respond.data;
            NSMutableArray *result = [NSMutableArray array];
            for (NSDictionary *data in array) {
                RecordDTO *dto = [[RecordDTO alloc] init];
                dto.cityName = data[@"vtg_scenic_cityname"];
                dto.scenicName = data[@"vtg_scenic_name"];
                dto.time = data[@"createtime"];//[data[@"createtime"] componentsSeparatedByString:@" "][0];
                dto.scenicArray = [NSMutableArray array];
                for (NSDictionary *cell in data[@"children"]) {
                    RecordDTO *dto1 = [[RecordDTO alloc] init];
                    dto1.cityName = cell[@"vtg_scenic_cityname"];
                    dto1.scenicName = cell[@"vtg_scenic_name"];
                    dto1.time = cell[@"createtime"];
                    [dto.scenicArray addObject:dto1];
                }
                dto.description = [dto tostring];
                [result addObject:dto];
            }
            respond.data = result;
        }
        completion(respond);
    }];
}

//获取周围景点
+(void)getNearSceniceRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib getNearSceniceRequestInfo:info completion:^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            NSMutableArray *result = [NSMutableArray array];
            for (NSDictionary *data in respond.data) {
                BasicMapAnnotation *pointAnnotation = [[BasicMapAnnotation alloc]initWithLatitude:[data[@"vtg_scenic_latitude"] doubleValue] andLongitude:[data[@"vtg_scenic_longitude"] doubleValue]];
                pointAnnotation.title = data[@"vtg_scenic_name"];//@"中山陵";
                pointAnnotation.vtg_language_id = data[@"vtg_language_id"];
                pointAnnotation.vtg_language_key = data[@"vtg_language_key"];
                pointAnnotation.vtg_scenic_id = data[@"vtg_scenic_id"];
                pointAnnotation.zipurl = data[@"zipFileUrl"];
                pointAnnotation.zoomScale = [data[@"vtg_scenic_zoom"] floatValue];
                pointAnnotation.type = [data[@"vtg_scenic_typeid"] integerValue];
                [result addObject:pointAnnotation];
            }
            respond.data = result;
        }

        completion(respond);
    }];
}

//获取城市列表
+(void)getCitylistRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib getCitylistRequestInfo:info completion:^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            NSArray *array = respond.data;
            NSMutableArray *result = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                CityDTO *dto = [[CityDTO alloc]init];
                dto.cityCode = dic[@"cityCode"];
                dto.cityId = dic[@"cityId"];
                dto.cityName = dic[@"cityName"];
                dto.languageKey = dic[@"languageKey"];
                [result addObject:dto];
            }
            respond.data = result;
        }
        completion(respond);
    }];
}

//获取城市下得景点
+(void)getCityscenicesRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib getCityscenicesRequestInfo:info completion:^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            NSArray *array = respond.data;
            NSMutableArray *result = [NSMutableArray array];
            for (NSDictionary *data in array) {
                
                ScenicScene *scenic = [db_Downloading getScenic:[NSString stringWithFormat:@"%@",data[@"vtg_scenic_id"]] language:[[DataCenter instance] getLanguageType]==zh_cn?@"zh-cn":@"en-us"];
                if (!scenic) {
                    scenic = [[ScenicScene alloc] init];
                    scenic.scenicId = [NSString stringWithFormat:@"%@",data[@"vtg_scenic_id"]];
                    scenic.isDownloading = NO;
                    scenic.needUpdate = NO;
                    scenic.language = [[DataCenter instance] getLanguageType]==zh_cn?@"zh-cn":@"en-us";
                }else {
                    if (!scenic.needUpdate) {
                        if ([scenic.zipFile isEqualToString:data[@"zipFile"]]) {
                            scenic.needUpdate = NO;
                        }else{
                            scenic.needUpdate = YES;
                        }
                    }
                }
                scenic.scenicName = data[@"vtg_scenic_name"];
                scenic.zipFile = data[@"zipFile"];
                scenic.zipSize = [data[@"zipSize"] floatValue];
                scenic.icon = data[@"vtg_scenic_icon"];
                [result addObject:scenic];
            }
            respond.data = result;
        }
        completion(respond);
    }];
}

//在线获取景点资源
+(void)getOnlineResourceRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib getOnlineResourceRequestInfo:info completion:^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            NSDictionary *dic = respond.data;
            ScenicScene *scenic = [[ScenicScene alloc] init];
            scenic.icon = dic[@"icon"];
            scenic.language = dic[@"language"];
            scenic.scenicId = dic[@"scenicId"];
            scenic.scenicName = dic[@"scenicName"];
            scenic.voice = dic[@"voice"];
            scenic.type = [dic[@"typeId"] integerValue];
            if (scenic.type == 1) {
                scenic.top_left = CGPointMake([dic[@"topLeft"][@"x"] doubleValue], [dic[@"topLeft"][@"y"] doubleValue]);//CGPointMake(118.856828,32.069052);//
                scenic.bottom_right = CGPointMake([dic[@"bottomRight"][@"x"] doubleValue], [dic[@"bottomRight"][@"y"] doubleValue]);//CGPointMake(118.863709,32.061034);//
                //            scenic.top_right = CGPointMake(scenic.bottom_right.x, scenic.bottom_right.y);
                //            scenic.bottom_left = CGPointMake(scenic.top_left.x, scenic.top_right.y);
            }

//            
            scenic.scenicPoints = [NSMutableArray array];
            for (NSDictionary *data in dic[@"children"]) {
                ScenicDTO *dto = [[ScenicDTO alloc] init];
                dto.vtg_language_id = data[@"vtg_language_id"];
                dto.vtg_language_key = data[@"vtg_language_key"];
                dto.vtg_resource_url = data[@"vtg_resource_url"];
                dto.vtg_scenic_id = data[@"vtg_scenic_id"];
                dto.GPS = CGPointMake([data[@"vtg_scenic_longitude"] doubleValue], [data[@"vtg_scenic_latitude"] doubleValue]);
                dto.vtg_scenic_name = data[@"vtg_scenic_name"];
                [scenic.scenicPoints addObject:dto];
            }
            respond.data = scenic;
        }
        completion(respond);
    }];
}

//在线语音下载
+(void)downloadCache:(NSString*)url completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib downloadCache:url completion:^(RespondDTO *respond) {
        completion(respond);
    }];
}
//离线获取景点资源
+(void)getOfflineResourceRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib getOfflineResourceRequestInfo:info completion:^(RespondDTO *respond) {
        completion(respond);
    }];
}

+(NSOperation*)downloadZip:(NSString*)url fileName:(NSString*)filename completion:(void(^)(RespondDTO *respond))completion{
    return [tour_lib downloadZip:url fileName:filename completion:completion];
}

//分享记录
+(void)shareRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib shareRequestInfo:info completion:^(RespondDTO *respond) {
        completion(respond);
    }];
}

//ad
+(void)adRequestInfo:(NSDictionary*)info completion:(void(^)(RespondDTO *respond))completion{
    [tour_lib adRequestInfo:info completion:^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            [DataCenter instance].adUrl = respond.data[@"linkUrl"];
        }
        completion(respond);
    }];
}

//loading
+(void)loadingRequestcompletion:(void(^)(RespondDTO *respond))completion{
    NSString *systype = [[UIDevice currentDevice] model];
    if ([systype isEqualToString:@"iPod touch"]) {
        systype = @"iPhone";
    }
    NSDictionary *info = @{@"SystemType": systype,@"AppVersion":[[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"],@"SystemVersion":[[UIDevice currentDevice] systemVersion]};
    [tour_lib loadingRequestInfo:info completion:^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            NSDictionary *dic = respond.data;
            [DataCenter instance].shareText = dic[@"shareInfo"][@"shareInfo"];
        }
        completion(respond);
    }];
}

//上传图片
+(void)uploadPic:(NSData*)imgData :(void(^)(RespondDTO *respond))completion{
    [tour_lib uploadPic:imgData :^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            NSDictionary *dic = respond.data;
            respond.data = dic[@"path"];
        }
        completion(respond);
    }];
}

@end
